package br.com.egg.finances.business.dao.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import br.com.egg.finances.business.exception.BusinessErrorException;

public class BDUtils {
	
	public static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	public static String DATABASE_URL = "jdbc:mysql://localhost/DEGGFINANCE";
	public static String DATABASE_USER = "root";
	public static String DATABASE_PASSWORD = "";
	
	public static Connection getConnection() {
		try {
			Class.forName(JDBC_DRIVER);
			return DriverManager.getConnection(DATABASE_URL, DATABASE_USER, DATABASE_PASSWORD);
		} catch (Exception e) {
			throw new BusinessErrorException(e);
		}
	}
	
	public static void closeResources(Connection connection, Statement statement, ResultSet resultSet) {
		try {
			if (isResultSetNotNullAndNotClosed(resultSet)) {
				resultSet.close();
			}
			
			if (isStatementNotNullAndNotClosed(statement)) {
				statement.close();
			}
			
			if (isConnectionNotNullAndNotClosed(connection)) {
				connection.close();
			}
		} catch (Exception e) {
			throw new BusinessErrorException(e);
		}
	}

	public static boolean isConnectionNotNullAndNotClosed(Connection connection) throws SQLException {
		return connection != null && !connection.isClosed();
	}

	public static boolean isStatementNotNullAndNotClosed(Statement statement) throws SQLException {
		return statement != null && !statement.isClosed();
	}
	
	public static boolean isResultSetNotNullAndNotClosed(ResultSet resultSet) throws SQLException {
		return resultSet != null && !resultSet.isClosed();
	}

}
